package net.thxjj.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import net.model.ActionType;
import net.model.TypeCmd;
import net.model.device.CmdBean;
import net.model.device.CmdParams;
import net.model.device.DeviceBean;
import net.model.deviceresp.DevRespBean;
import net.thxjj.controller.base.BaseController;
import net.thxjj.error.ErrCode;
import net.thxjj.error.ErrorCode;
import net.thxjj.netty.DeviceSocketMap;
import net.thxjj.service.IDeviceService;
import net.thxjj.service.IProductService;
import net.thxjj.standard.ResponseModel;
import net.thxjj.standard.ResultEnum;
import net.util.ParameterMap;
import net.util.Tools;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/user")
public class DeviceController extends BaseController {
	
	@Autowired
	private IDeviceService ideviceService;

	@Autowired
	private IProductService iProductService;
	
	
	/**
	 * 校验下发命令合规性并且下发命令
	 * @return
	 */
	@RequestMapping(value="/socket",method=RequestMethod.POST)
	@ResponseBody
	public Object command(@RequestBody JSONObject json){


		long user_id = json.getLongValue("user_id");
		//判断用户id是否为空
		if(user_id==0){
			return ResponseModel.getModel(ErrCode.PROPERTY_NOT_EXIST_ERROR,null);
		}

		String info = json.getString("info");


		//判断info是否为空
		if(StringUtils.isEmpty(info)){
			return ResponseModel.getModel(ErrCode.PROPERTY_NOT_EXIST_ERROR,null);
		}

		try {
			JSONObject jsonObject = JSON.parseObject(info);

			boolean paramsFlag = jsonObject.containsKey("params");
			boolean actionFlag = jsonObject.containsKey("action");
			boolean msgId = jsonObject.containsKey("msgId");
			//判断外层参数是否合法
			if(!paramsFlag || !actionFlag || !msgId){
				return ResponseModel.getModel(ErrCode.PROPERTY_NOT_EXIST_ERROR,null);
			}

			//判断action值是否合法
			String action = jsonObject.getString("action");
			if(!ActionType.APP_SEND.getName().equals(action)){

				return ResponseModel.getModel(ErrCode.ACTION_ERROR,null);
			}

			//判断设备设备码和控制码是否合法
			JSONObject params = jsonObject.getJSONObject("params");
			String devTid = params.getString("devTid");
			String ctrlKey = params.getString("ctrlKey");

			if(StringUtils.isEmpty(devTid) || StringUtils.isEmpty(ctrlKey)){
				return ResponseModel.getModel(ErrCode.PROPERTY_NOT_EXIST_ERROR,null);
			}

			//判断设备是否存在
			ParameterMap parameterMap = new ParameterMap();
			parameterMap.put("device_id",devTid);
			parameterMap.put("ctrl_key",ctrlKey);
			DeviceBean deviceBean = ideviceService.getDevice(parameterMap);
			if(deviceBean==null){
				return ResponseModel.getModel(ErrCode.DEVICE_NOT_EXIST_ERROR,null);
			}

			//判断设备是否属于该用户
			List<String> list_devTids = ideviceService.getUserBindDevTidList(user_id);
			if(!list_devTids.contains(devTid)){
				return ResponseModel.getModel(ErrCode.DEVICE_NOT_BELONG_CLIENT_ERROR,null);
			}

            //判断设备是否在线
			if(deviceBean.getNetStatus()!=1){
				return ResponseModel.getModel(ErrCode.DEVICE_NOT_ONLINE,null);
			}


			CmdBean cmdBean =  JSONObject.parseObject(info, CmdBean.class);

			//params字段缺失报错
			if(cmdBean.getParams()==null){

				return ResponseModel.getModel(ErrCode.PARAMS_IS_NOT_EXIST_ERROR,null);
			}

			CmdParams cmdParams = cmdBean.getParams();

			//params内data字段缺失报错
			if(cmdParams.getData()==null){

				return ResponseModel.getModel(ErrCode.DATA_CAN_NOT_EMPTY_ERROR,null);
			}

			HashMap<String,Object> map = cmdParams.getData();
			//data字段属性字段必填项cmdId缺失报错
			if(!map.containsKey("cmdId")){
				return ResponseModel.getModel(ErrCode.CMDID_CAN_NOT_EMPTY_ERROR,null);
			}

			String prodKey = deviceBean.getProdKey();
			Integer cmdid = (Integer) map.get("cmdId");
			ParameterMap property = iProductService.getProductPropertys(cmdid, prodKey, TypeCmd.TYPE_APP_SEND);

			//判断是否含有cmdId关键字段
			if(property==null){
				return ResponseModel.getModel(ErrCode.CMD_NOT_EXIST_ERROR,null);
			}

			String content = (String)property.get("content");
			if(StringUtils.isEmpty(content)){
				return ResponseModel.getModel(ErrCode.INSTRUCTION_NOT_EXIST_ERROR,null);
			}

			//判断上报的数据是否合法
			ErrCode flag = iProductService.isLawFul(content,map);

			//记录日志并实时发送
			if(flag!=ErrCode.SUCCESS){
				return ResponseModel.getModel(flag,null);
			}

			ParameterMap parameterMap1 = new ParameterMap();
			parameterMap1.put("device_id",deviceBean.getDevTid());
			parameterMap1.put("log_type",2);
			parameterMap1.put("content",info);
			parameterMap1.put("create_time",System.currentTimeMillis());
			ideviceService.insertDevSendLog(parameterMap1);

			Channel channel = DeviceSocketMap.getChannelByDevTid(devTid);
			if(channel!=null){
				channel.writeAndFlush(info);
			}


		}catch (JSONException e){
			ResponseModel.getModel(ErrCode.JSON_FORMAT_ERROR,null);
		}
		return ResponseModel.getModel(ErrCode.SUCCESS,null);
	}


}
